package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class CustomerDAO {
	private static final String jndi = "java:comp/env/jdbc/struts";
	private DataSource ds = null;
	

	private static final String SELECT_SQL = "select custid , password , email , birth from customer where custid =?";

	public CustomerDAO() {
		try {
			Context ctx = new InitialContext();
			ds = (DataSource) ctx.lookup(jndi);
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	public CustomerBean select(String id) {
		 Connection conn = null;
		 ResultSet rs = null;
		 PreparedStatement pstmt = null;
		 CustomerBean result = null;

		try {
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(SELECT_SQL);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				result = new CustomerBean();
				result.setCustid(rs.getString("CUSTID"));
				result.setPassword(rs.getString("PASSWORD"));
				result.setEmail(rs.getString("EMAIL"));
				result.setBirth(rs.getDate("BIRTH"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs!=null) {
				try {
					rs.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
			if (pstmt != null) {
				try {
					pstmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

		return result;
	}
}
